﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Helpers;
using MvcMusicStore.Models;
using System.Data.Entity;



namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
       private MusicShopDBEntities model = new MusicShopDBEntities();
           

        // GET: /Store/
        public ActionResult Index()
        {
                var genres = model.Genre.ToList();

                return View(genres);
        }
       

        // GET: /Store/GenreMenu
        [ChildActionOnly]
        public ActionResult GenreMenu()
        {
                var genres = model.Genre.ToList();
                return PartialView(genres);
        }
        //
        // GET: /Store/Browse
        public ActionResult Browse(string genre)
        {
            // Retrieve Genre and its Associated Albums from database

                var genreModel = model.Genre.Include("Album")
                    .Single(g => g.nameGenre == genre);

                return View(genreModel);
        }


        //
        // GET: /Store/Details
        public ActionResult Details(int id)
        {
                var album = model.Album.Include("Song").Include("Author").Include("Genre")
                    .Single(a => a.id == id);

                return View(album);
        }
        public ActionResult Song(int id)
        {
                var song = model.Song.Include("Album")
                    .Single(a => a.id == id);

                return View(song);
            
        }
        protected override void Dispose(bool disposing)
        {
            model.Dispose();
            base.Dispose(disposing);
        }

        //GET: /Store/Download - stream media
        [HttpGet]
        [HttpHeadersNoCache]
        public ActionResult Download([Bind(Prefix = "id")]int? songId)
        {
            if (!songId.HasValue) return HttpNotFound();

            bool isDemo  = true;//= (0 != Environment.TickCount % 2);

            if (!User.Identity.IsAuthenticated)
            {
                isDemo = true;
            }
            else
            {
                //var isSongPurchased = model.aspnet_Users.Where(u => u.UserName == User.Identity.Name)
                //                                        .Include(t => t.Song)
                //                                        .Count(s => s.Song.Any(i => i.id == songId.Value));
                var isPurchasedSong = (from u in model.aspnet_Users
                                          where u.UserName == User.Identity.Name
                                          from s in u.Song
                                          where s.id == songId.Value
                                          select s.id).Any();

                if (isPurchasedSong)
                {
                    isDemo = false;
                }
                else
                {

                    //var purchasedAlbumsCount = model.aspnet_Users.Where(u => u.UserName == User.Identity.Name)
                    //                                        .Include(a => a.Album)
                    //                                        .Include(s => s.Song)
                    //                                       .Count(s => s.Song.Any(i => i.id == songId.Value));

                    var isPurchasedAlbum = (from u in model.aspnet_Users
                                                where u.UserName == User.Identity.Name
                                                from a in u.Album
                                                from s in a.Song
                                                where s.id == songId.Value
                                                select s.id).Any();
                    if (isPurchasedAlbum)
                    {
                        isDemo = false;
                    }
                }

                
            }
            


            string contentType;
            Stream clientStream;
            try
            {
                StorageHelper.SelectSong(songId.Value, out contentType, out clientStream, isDemo);
            }
            catch
            {
                return HttpNotFound();
            }
            return new FileStreamResult(clientStream, contentType);

        }

    }
    public class HttpHeadersNoCacheAttribute : ActionFilterAttribute
    {
        private readonly KeyValuePair<string, string>[] headers =
            {
                new KeyValuePair<string, string>("Cache-Control", "no-cache, must-revalidate"),
                new KeyValuePair<string, string>("Pragma", "no-cache"),
                new KeyValuePair<string, string>("Expires", "0")
            };

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            foreach (var header in headers)
            {
                filterContext.HttpContext.Response.AppendHeader(header.Key, header.Value);
            }
            base.OnResultExecuted(filterContext);
        }
    }

    
}
